<?php
namespace app\admin\controller;
use app\model\Report as ReportModel;
use think\Db;


class Report extends Base
{
    public function __construct(){
        $model = new ReportModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '新闻资讯';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $model = $this->model;

        $fields = [
            'title'=>['name'=>'标题','type'=>'text','valids'=>['required']],
            'content'=>['name'=>'内容','type'=>'textarea','valids'=>['required']],
            'summarize'=>['name'=>'概括','type'=>'textarea'],
            'cdate'=>['name'=>'日期','type'=>'date'],
        ];
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);
    }

    public function assignSearchs(){
        $model = $this->model;

        $search_params = [
            [
                // ['key'=>'title','name'=>'标题','type'=>'text'],
                // ['key'=>'cdate','name'=>'日期','type'=>'date'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function getMap(){
        $map_params = [
            ['key'=>'title','type'=>'='],
            ['key'=>'cdate','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        // if (isSearchParam('start_time')) {
        //     $map[] = ['ctime','>=',strtotime(input('start_time'))];
        // }
        // if (isSearchParam('end_time')) {
        //     $map[] = ['ctime','<=',strtotime(input('end_time'))];
        // }
        switch (input('date_type')) {
            case '1':
                $map[] = ['cdate','=',date('Y-m-d')];
                break;
            case '2':
                $date = date('Y-m-d',strtotime('-1 days'));
                $map[] = ['cdate','=',$date];
                break;
            case '3':
                $week_start = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
                $map[] = ['cdate','>=',date('Y-m-d',$week_start)];
                break;
            default:
                if (!empty(input('start_time'))) {
                    $map[] = ['cdate','>=',input('start_time')];
                }
                if (!empty(input('end_time'))) {
                    $map[] = ['cdate','<=',input('end_time')];
                }
                break;
        }
        

        return $map;
    }

    public function index(){
        $model = $this->model;
        $map = $this->getMap();
        $this->assignSearchs();

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();

        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            if (!empty($vo['user_id'])) {
                $user = Db::name('user')->where('id','in',explode(',', $vo['user_id']))->column('truename');
                $list['data'][$k]['user'] = implode('、',$user);
            }else{
                $list['data'][$k]['user'] = '所有用户';
            }
        }

        $users = Db::name('user')->select();

        return view('index', [
            'list'=>$list,
            'page'=>$page,
            'date_type'=>['自定义','今日','昨日','本周'],

            'users'=>$users
        ]);
    }

    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['title','content'],
                'nomust'=>['summarize','cdate']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }

            if (!empty($save_data['summarize'])) {
                $save_data['status'] = 1;
            }
        }
        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        if (request()->isPost()) {
            $fields = [
                'nomust'=>['title','content','summarize','cdate']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
        }
        return parent::updateData($id,$save_data);
    }

    public function detail($id,$type){
        $model = $this->model;
        $data = $model->where('id',$id)->find();
        return json(['status'=>1,'data'=>$data[$type]]);
    }

    public function mailContent($id){
        $model = $this->model;
        $data = $model->where('id',$id)->find();
        $content = [];
        // $content[] = '<div style="text-align:center;">报告标题：'.$data['title'].'</div>';
        $content[] = "您好！";
        $content[] = "\r\n";
        $content[] = "为助力您及时掌握近期各领域核心动态，我们结合资讯热度、行业影响力及实用价值，筛选整理了 ".date('Y年m月d日',strtotime($data['cdate']))." 日重点热点内容。以下为当日核心热点（完整版 TOP10 资讯可按需补充），供您快速了解关键信息：";
        $content[] = "\r\n";
        $content[] = $data['content'];
        $content[] = "\r\n";
        $content[] = '报告总结：'.$data['summarize'];

        return json(['status'=>1,'data'=>implode("\r\n",$content)]);
    }


    public function setUserId(){
        $model = $this->model;
        $fields = [
            'nomust'=>['report_id','user_id']
        ];
        $params = paramFilter(request()->param(),$fields);
        $save_data = [
            'user_id'=>empty($params['user_id']) ? null : implode(',',$params['user_id'])
        ];

        $model->where('id',$params['report_id'])->update($save_data);
        $this->success('设置成功');
    }

    public function sendEmail($id){
        $model = $this->model;
        $data = $model->where('id',$id)->find();
        if (empty($data)) {
            $this->error('报告不存在');
        }
        if ($data['status'] == 0) {
            $this->error('报告内容还在生成中，请稍后再发送');   
        }

        $content = $this->mailContent($data['id']);
        $content = json_decode($content->getContent(),true);
        $content = $content['data'];

        $user_ids = $data['user_id'];
        if (!empty($user_ids)) {
            $users = Db::name('user')->where('id','in',explode(',',$user_ids))->select();
        }else{
            $users = Db::name('user')->select();
        }

        foreach ($users as $user) {
            if (empty($user['email'])) {
                continue;
            }
            // dump($user['email']);
            // dump($data['title']);
            // dump($content);
            $email_content = "尊敬的 ".$user['truename']."：\r\n".$content;
            $email_content = myTextareaShow($email_content);
            $result = sendMail($user['email'],'AI洞察',$data['title'],$email_content);
            // dump($result);
        }

        $model->where('id',$id)->update(['status'=>10,'utime'=>time()]);

        $this->success('发送成功');exit();
    }
   
}
